<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="商品名">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="主标签">
        <template slot-scope="scope">
          <span>{{ scope.row.mainType }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="副标签">
        <template slot-scope="scope">
          <span>{{ scope.row.mainType }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="价格">
        <template slot-scope="scope">
          <span>{{ scope.row.prices }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="销量">
        <template slot-scope="scope">
          <span>{{ scope.row.sellCount }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="点击量">
        <template slot-scope="scope">
          <span>{{ scope.row.viewCount }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="关键字">
        <template slot-scope="scope">
          <span>{{ scope.row.keywords }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <router-link :to="'/product/edit/'+row.id">
            <el-button type="primary" size="medium " icon="el-icon-edit">
              编辑
            </el-button>
          </router-link>
          <el-button type="danger" size="medium " icon="el-icon-delete" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="Name" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="mainType" prop="mainType">
          <el-input v-model="temp.mainType" />
        </el-form-item>
        <el-form-item label="subType" prop="subType">
          <el-input v-model="temp.subType" />
        </el-form-item>
        <el-form-item label="prices" prop="prices">
          <el-input v-model="temp.prices" />
        </el-form-item>
        <el-form-item label="keywords" prop="keywords">
          <el-input v-model="temp.keywords" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchProduct, updateProduct, createProduct, deleteProduct, fetchMerchantProduct } from '@/api/product'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { mapGetters } from 'vuex'

export default {
  name: 'ProductList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      downloadLoading: false,
      listQuery: {
        page: 1,
        size: 20
      },
      dialogStatus: 'update',
      dialogFormVisible: false,
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      temp: {
        name: 'temp',
        mainType: 'temp',
        subType: 'temp',
        prices: 0,
        keywords: 'temp'
      }
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      const { page, size } = this.listQuery
      if (this.roles.includes('merchant')) {
        fetchMerchantProduct({ page: page - 1, size }).then(response => {
          this.list = response.items
          this.total = response.total
          this.listLoading = false
        })
      } else {
        fetchProduct({ page: page - 1, size }).then(response => {
          this.list = response.items
          this.total = response.total
          this.listLoading = false
        })
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该商品,是否确认', '提示')
        .then(() => {
          deleteProduct(row).then(res => {
            this.$notify({
              title: '成功',
              message: '成功删除',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          }, _ => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
        })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: 'temp',
        mainType: 'temp',
        subType: 'temp',
        prices: 0,
        keywords: 'temp'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'name', 'mainType', 'subType', 'prices', 'sellCount', 'viewCount', 'keywords']
        const data = this.formatJson(tHeader)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'product-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) return
        createProduct(this.temp).then(() => {
          this.list.unshift(this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '成功创建商品',
            type: 'success',
            duration: 200
          })
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) { return }
        const tempData = Object.assign({}, this.temp)
        updateProduct(tempData).then(() => {
          const index = this.list.findIndex(v => v.id === tempData.id)
          this.list.splice(index, 1, this.temp)
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '成功更新商品',
            type: 'success',
            duration: 2000
          })
        })
      })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
